package com.example.hyg_veintype;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import com.example.hyg_veintype.constant.ble.BleRssiDevice;
import com.example.hyg_veintype.utils.bleUtil.MyBleWrapperCallback;
import com.hyg.lib_common.Base.BaseApplication;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.model.BleFactory;
import cn.com.heaton.blelibrary.ble.utils.UuidUtils;

public class MyApplication extends BaseApplication {
    private static MyApplication mApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        initBle();
        //bugly
        initBygly();
        Log.d("initUUid=========", "主服务的UUID"+ UuidUtils.uuid16To128("FFE5"));
        Log.d("initUUid=========","可写特征的uuid"+ UuidUtils.uuid16To128("FFE9"));
        Log.d("initUUid=========", "可通知特征的uuid"+ UuidUtils.uuid16To128("fd03"));
    }
    private void initBygly(){
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setBuglyLogUpload(processName == null || processName.equals(packageName));
        // 初始化Bugly 建议在测试阶段建议设置成true，发布时设置为false。
        CrashReport.initCrashReport(context, "a8158bbd67", true, strategy);
        // 如果通过“AndroidManifest.xml”来配置APP信息，初始化方法如下
        // CrashReport.initCrashReport(context, strategy);
    }

    //初始化蓝牙
    private void initBle() {
        /*ScanFilter scanFilter = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            scanFilter = new ScanFilter.Builder()
                    .setServiceUuid(ParcelUuid.fromString(UuidUtils.uuid16To128("fff0")))//8.0以上手机后台扫描，必须开启
//                    .setDeviceAddress("00:3D:00:00:00:18")
//                    .setDeviceName("QCAR")
                            .build();
        }*/
        Ble.options()
                .setLogBleEnable(false)//设置是否输出打印蓝牙日志
                .setThrowBleException(true)//设置是否抛出蓝牙异常
                .setLogTAG("AndroidBLE")//设置全局蓝牙操作日志TAG
                .setAutoConnect(false)//设置是否自动连接
                .setIgnoreRepeat(false)//设置是否过滤扫描到的设备(已扫描到的不会再次扫描)
                .setConnectFailedRetryCount(3)//连接异常时（如蓝牙协议栈错误）,重新连接次数
                .setConnectTimeout(10 * 1000)//设置连接超时时长
                .setScanPeriod(12 * 1000)//设置扫描时长
                .setMaxConnectNum(1)//最大连接数量
//                .setScanFilter(scanFilter)
                .setUuidService(UUID.fromString(UuidUtils.uuid16To128("FFE5")))//设置主服务的uuid
                .setUuidWriteCha(UUID.fromString(UuidUtils.uuid16To128("FFE9")))//设置可写特征的uuid
//                .setUuidReadCha(UUID.fromString(UuidUtils.uuid16To128("fd02")))//设置可读特征的uuid （选填）
                .setUuidNotifyCha(UUID.fromString(UuidUtils.uuid16To128("fd03")))//设置可通知特征的uuid （选填，库中默认已匹配可通知特征的uuid）
                .setFactory(new BleFactory() {//实现自定义BleDevice时必须设置
                    @Override
                    public BleRssiDevice create(String address, String name) {
                        return new BleRssiDevice(address, name);//自定义BleDevice的子类
                    }
                })
                .setBleWrapperCallback(new MyBleWrapperCallback())
                .create(mApplication, new Ble.InitCallback() {
                    @Override
                    public void success() {
                        BleLog.e("MainApplication", "初始化成功");
                    }

                    @Override
                    public void failed(int failedCode) {
                        BleLog.e("MainApplication", "初始化失败：" + failedCode);
                    }
                });
    }
    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
